package com.Xht.www.servlet;

//后端响应获取用户积分信息的请求

import com.Xht.www.dao.UserPointsDAO;
import com.Xht.www.po.UserPointsPO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/getPointsInfo")
public class PointsServlet extends HttpServlet {
    private UserPointsDAO userPointsDAO = new UserPointsDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        if ("all".equals(action)) {
            // 返回所有用户的积分信息
            List<UserPointsPO> allPoints = userPointsDAO.getAllUserPoints();
            StringBuilder json = new StringBuilder("[");
            for (int i = 0; i < allPoints.size(); i++) {
                UserPointsPO points = allPoints.get(i);
                json.append("{\"userId\":").append(points.getUserId())
                        .append(",\"totalPoints\":").append(points.getTotalPoints())
                        .append(",\"consecutiveDays\":").append(points.getConsecutiveDays())
                        .append(",\"cumulativeDays\":").append(points.getCumulativeDays())
                        .append("}");
                if (i < allPoints.size() - 1) {
                    json.append(",");
                }
            }
            json.append("]");
            out.print(json.toString());
        } else {
            // 返回单个用户的积分信息
            int userId = Integer.parseInt(request.getParameter("userId"));
            UserPointsPO userPoints = userPointsDAO.getUserPointsById(userId);
            if (userPoints != null) {
                String json = "{\"totalPoints\":" + userPoints.getTotalPoints() +
                        ",\"consecutiveDays\":" + userPoints.getConsecutiveDays() +
                        ",\"cumulativeDays\":" + userPoints.getCumulativeDays() + "}";
                out.print(json);
            } else {
                out.print("{}");
            }
        }
        out.flush();
    }
}
